import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

/**
 * 定义与actions里的函数:
 * 须返回Promise实例，以便我们能够知道数据在何时更新
 */
export const createStore = () => {
	return new Vuex.Store({
		state: () => ({
      posts: [],
      authInfo: null
		}),
		mutations: {
      setPosts (state, payload) {
        state.posts = payload
      },
      initToken(state, payload){
        state.authInfo = payload
      }
		},
		actions: {
      async getPosts ({ commit }) {
        const { data } = await axios.get('https://cnodejs.org/api/v1/topics')
        commit('setPosts', data.data)
      }
		}
	})
} 